package site.xuqing.autohelpertools.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.view.accessibility.AccessibilityNodeInfo;

import org.json.JSONArray;
import org.json.JSONObject;

import androidx.annotation.Nullable;
import site.xuqing.autohelperengine.AutoHelper;
import site.xuqing.autohelperengine.listener.OnCurrentScreenDataListener;
import site.xuqing.autohelpertools.util.SharedPreferencesUtil;

public class ScreenService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        AutoHelper.getInstance().setOnCurrentScreenDataListener(new OnCurrentScreenDataListener() {
            @Override
            public void onResult(AccessibilityNodeInfo root, String currentScreenClassName) {
                if (currentScreenClassName.contains("site.xuqing.autohelpertools")){
                    return;
                }
                try {
                    System.out.println(currentScreenClassName);
                    //解析数据
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("className",currentScreenClassName);
                    JSONArray jsonArray = new JSONArray();
                    jsonObject.put("nodes", jsonArray);
                    getJson(root, jsonArray);

                    SharedPreferencesUtil.addScreenData(jsonObject.toString());
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    public void getJson(AccessibilityNodeInfo node, JSONArray jsonArray) throws Exception {
        if (node == null) {
            return;
        }
        JSONArray jsonArrayChild = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("className", node.getClassName());
        jsonObject.put("text", node.getText());
        jsonObject.put("desc", node.getContentDescription());
        jsonObject.put("id", node.getViewIdResourceName());
        jsonObject.put(node.hashCode() + "", jsonArrayChild);
        jsonArray.put(jsonObject);
        for (int i = 0; i < node.getChildCount(); i++) {
            getJson(node.getChild(i), jsonArrayChild);
        }
    }
}
